import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/pages/home/setting/dialog/command_dialog_interface.dart';
import 'package:tracker/pages/home/setting/dialog/custom_command_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/deep_sleep_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/light_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/location_interval_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/location_priority_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/low_voltage_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/offline_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/over_speed_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/power_off_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/simple_command_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/vibration_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/work_mode_dialog.dart';
import 'package:tracker/pages/home/setting/model/get_setting_resp.dart';
import 'package:tracker/pages/home/setting/model/remote_setting_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 设置 页面
class RemoteSettingPage extends ConsumerStatefulWidget {
  const RemoteSettingPage({super.key});

  @override
  ConsumerState<RemoteSettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends ConsumerState<RemoteSettingPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  List<RemoteSettingData> remoteSettingList = [];

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      _fetchSettingList();
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchSettingList() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final queryParams = {
      'imei': deviceInfo.imei,
    };
    final res = await get<RemoteSettingListResp, RemoteSettingListResp>('/command/list',
        queryParameters: queryParams, decodeType: RemoteSettingListResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        // 过滤某些指令
        final noFilterList = [
          'nmset',
          'c',
          'nmdw',
          'senalm',
          'offline',
          'timer',
          'exbatalm',
          'speed',
          'wake',
          'flytime',
          'reset',
          'common'
        ];
        final settingList =
            resp.data?.where((element) => noFilterList.contains(element.cmdCode?.toLowerCase())).toList();
        setState(() {
          remoteSettingList = settingList ?? [];
        });
      } else {
        ToastUtils.showToast(resp.msg ?? '获取远程设置列表失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取远程设置列表失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取远程设置列表失败: msg: $msg, code: $code');
    });
  }

  Widget _buildSettingList() {
    return Container(
      color: Colors.grey.shade100,
      child: ListView.separated(
        shrinkWrap: true,
        physics: const ScrollPhysics(),
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        itemBuilder: (context, index) {
          final item = remoteSettingList[index];
          return _RemoteSettingTile(
            title: item.cmdName ?? '',
            subtitle: item.introduction ?? '',
            onTap: () { _onListItemTap(item); },
          );
        },
        separatorBuilder: (context, index) {
          return const SizedBox(height: 10);
        },
        itemCount: remoteSettingList.length,
      ),
    );
  }

  /// 点击指令
  _onListItemTap(RemoteSettingData remoteSettingData) async {
    XLogger.info('点击指令: ${remoteSettingData.cmdName}，指令编码：${remoteSettingData.cmdCode}');
    CommandDialogInterface? commandDialogInterface;
    switch (remoteSettingData.cmdCode!.toLowerCase()) {
      case 'nmset':
        // 工作模式
        commandDialogInterface = WorkModeDialog(
            scaffoldKey: _scaffoldKey, cmdCode: remoteSettingData.cmdCode, onConfirm: _onSendCommandClickCallback);
        break;
      case 'c':
        // 立即定位
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'nmdw':
        // 定位优先级
        commandDialogInterface = LocationPriorityDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'senalm':
        // 震动报警
        commandDialogInterface = VibrationAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'factory':
        // 恢复出厂设置
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'factoryall':
        // 恢复出厂设置（所有参数）
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'offline':
        // 远程开关机
        commandDialogInterface = OfflineDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'timer':
        // 定位间隔
        commandDialogInterface = LocationIntervalDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'poweralm':
        // 断电报警
        commandDialogInterface = PowerOffAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'exbatalm':
        // 低电压报警
        commandDialogInterface = LowVoltageAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'speed':
        // 超速报警
        commandDialogInterface = OverSpeedAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'lightalm':
        // 光感报警
        commandDialogInterface = LightAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'wake':
        // 立即定位(唤醒)
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'flytime':
        // 深度休眠
        commandDialogInterface = DeepSleepDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'reset':
        // 远程重启
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'common':
        // 文本指令下发
        commandDialogInterface = CustomCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      default:
        ToastUtils.showToast('暂不支持该指令');
        break;
    }
    // 获取用户指令配置
    final userSettingRes = await _getUserSetting(remoteSettingData.cmdCode!);
    userSettingRes.when(success: (resp) {
      if (resp.code == 200) {
        commandDialogInterface?.updateCmdContent(resp.data?.cmdContent ?? '');
        commandDialogInterface?.show(context);
      } else {
        ToastUtils.showToast(resp.msg ?? '获取用户指令配置失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取用户指令配置失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取用户指令配置失败: msg: $msg, code: $code');
    });
  }

  Future<Result<GetSettingResp>> _getUserSetting(String cmdCode) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'cmdCode': cmdCode,
    };
    final res =
        await post<GetSettingResp, GetSettingResp>('/command/getSetting', data: postData, decodeType: GetSettingResp());
    return res;
  }

  _onSendCommandClickCallback(String cmdContent) async {
    XLogger.info('发送指令: $cmdContent');
    final deviceInfo = ref.read(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'content': cmdContent,
      'cmdCode': cmdContent.split(',')[0],
    };
    ToastUtils.showLoading(status: '发送中...');
    final res = await post<BaseResp, BaseResp>('/command/send', data: postData, decodeType: BaseResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        ToastUtils.showToast('发送成功');
      } else {
        ToastUtils.showToast(resp.msg ?? '发送失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: const Text(
          '远程设置',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: _buildSettingList(),
    );
  }
}

class _RemoteSettingTile extends StatelessWidget {
  final String title;
  final String subtitle;
  final VoidCallback onTap;
  const _RemoteSettingTile({required this.title, required this.subtitle, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: AppTheme.themeConfig.primaryColor.withOpacity(0.1),
            width: 1,
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.04),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            // 图标容器
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                    AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                  ],
                ),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                Icons.settings_remote,
                color: AppTheme.themeConfig.primaryColor,
                size: 24,
              ),
            ),
            const SizedBox(width: 16),
            // 文字信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                      color: AppTheme.themeConfig.primaryTextColor,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 13,
                      color: AppTheme.themeConfig.secondaryTextColor,
                      height: 1.3,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            // 箭头图标
            Container(
              padding: const EdgeInsets.all(6),
              decoration: BoxDecoration(
                color: AppTheme.themeConfig.primaryColor.withOpacity(0.08),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.arrow_forward_ios,
                color: AppTheme.themeConfig.primaryColor,
                size: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
